package io.sundial.task.hibernate;

import io.sundial.hibernate.SessionFactoryRepository;
import io.sundial.hibernate.TrxRNCall;
import io.sundial.hibernate.TrxVNCall;
import io.sundial.hibernate.TrxVTCall;
import io.sundial.repository.RepositoryException;
import io.sundial.task.Scheduling;
import io.sundial.task.SchedulingRepository;
import org.hibernate.Session;
import org.hibernate.query.Query;

import java.util.Enumeration;

/**
 * 调度记录仓储Hibernate实现
 *
 * @author Payne 646742615@qq.com
 * 2018/12/29 11:40
 */
public class HibernateSchedulingRepository extends SessionFactoryRepository implements SchedulingRepository {

    @Override
    public Scheduling find(final Scheduling.Key key) {
        return doReadonly(new TrxRNCall<Scheduling>() {
            @Override
            public Scheduling call(Session sex) {
                return sex.get(Scheduling.class, new Scheduling(key));
            }
        });
    }

    @Override
    public void save(final Scheduling.Key key, final Scheduling value) throws RepositoryException {
        doTransaction(new TrxVTCall<RepositoryException>() {
            @Override
            public void call(Session sex) {
                sex.save(value);
            }
        });
    }

    @Override
    public void replace(Scheduling.Key key, Scheduling value) throws RepositoryException {

    }

    @Override
    public Scheduling remove(Scheduling.Key key) {
        return null;
    }

    @Override
    public boolean contains(Scheduling.Key key) {
        return false;
    }

    @Override
    public Enumeration<Scheduling.Key> keys() {
        return null;
    }

    @Override
    public Enumeration<Scheduling> values() {
        return null;
    }

    @Override
    public void toFinished(final Scheduling.Key key) {
        doTransaction(new TrxVNCall() {
            @Override
            public void call(Session sex) {
                Query<Object> query = sex.createNamedQuery("Scheduling-toFinished", null);
                query.setParameter("taskName", key.getTaskName());
                query.setParameter("taskGroup", key.getTaskGroup());
                query.setParameter("time", key.getTime());
                query.executeUpdate();
            }
        });
    }
}
